package com.biz.service.base;

import com.alibaba.fastjson.JSON;
import com.biz.conf.Global;
import com.biz.model.Hmodel.TRefundLog;
import com.biz.model.Hmodel.TorderMain;
import com.biz.model.Pmodel.PorderMain;
import com.biz.model.Pmodel.basic.PorderSend;
import com.biz.model.Pmodel.basic.Ppics;
import com.biz.model.Pmodel.basic.PwxGoodsStockbak;
import com.framework.dao.hdao.BaseDaoI;
import com.framework.dao.mdao.DaoSupport;
import com.framework.model.Pager;
import com.framework.model.Paging;
import com.framework.utils.ConfigUtil;
import com.framework.utils.StringUtil;
import com.framework.utils.Tools;
import com.framework.utils.URLConectionUtil;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*************************************************************************
 * create by lzq
 *
 * 文件名称 ：OrderServiceI.java 描述说明 ：
 *
 * 版权信息 : Copyright (c) 2015 扬州北斗软件有限公司
 **************************************************************************/

@Service("orderService")
public class OrderServiceImpl extends BaseServiceImpl<TorderMain> implements OrderServiceI {

    @Resource(name = "daoSupport")
    private DaoSupport dao;

    @Autowired
    private BaseDaoI baseDao;

    @Autowired
    private BaseDaoI<TRefundLog> refundLogDao;

    @Autowired
    private BaseDaoI<TorderMain> torderMainDao;

    @Override
    public Paging queryOrders(Map map)throws Exception{
        int limit = Integer.parseInt(map.get("limit").toString());
        int offset = Integer.parseInt(map.get("offset").toString());
        Pager<Map<String, Object>> pager = new Pager();
        pager.setParameters(map);
        pager.setStartRecord(offset);
        pager.setPageSize(limit);

        Pager<Map<String, Object>> pager_back = (Pager<Map<String, Object>>) dao
                .findForPager1("OrderDao.findPageShopBuyOrder",
                        "OrderDao.countShopBuyOrder", pager);
        //封装成适合前台使用的格式
        Paging paging = new Paging<>();
        paging.setRows(pager_back.getExhibitDatas());
        paging.setTotal((long) pager_back.getRecordCount());
        return paging;
    }

    @Override
    public List<PorderMain> exportExcel_shopDeMain(
            Map<String, Map<String, Object>> maps) throws Exception {

        return (List<PorderMain>) dao.findForList(
                "OrderDao.exportExcel_shopDeMain", maps);
    }

    @Override
    public Pager<Map> queryWineApplys(Pager pager) throws Exception {
        return dao.findForPager1("OrderDao.queryWineApplys","OrderDao.queryWineApplysCount",pager);
    }


    @Override
    public Map<String, Object> findOrderInfoById(String id,String detailId) throws Exception {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("id", id);
        param.put("detailId",detailId);
        param.put("sameCode","");
        Map<String, Object> order = (Map<String, Object>) dao.findForObject(
                "OrderDao.findOrderInfoById", param);
        List<Map<String, Object>> listDetail = (List<Map<String, Object>>) dao
                .findForList("OrderDao.findOrderDetailById", param);
        param.put("detailId",listDetail.get(0).get("id"));
        /*Map<String, Object> listRefund = (Map<String, Object>) dao
                .findForObject("OrderDao.findOrderRefundById", param);*/
        Map<String, Object> orderSend = (Map<String, Object>) dao
                .findForObject("OrderDao.findOrderSendById", param);

        List<Map<String, Object>> quanDetail = (List<Map<String, Object>>) dao
                .findForList("OrderDao.findBalance90DetailById", param);

        order.put("listDetail", listDetail);
        order.put("orderSend", orderSend);
        //order.put("orderRefund", listRefund);
        order.put("quanDetail", quanDetail);
        return order;
    }

    @Override
    public List<PorderSend> orderSend(String orderid) throws Exception {

        Map<String, Object> map = new HashMap<>();
        map.put("orderid", orderid);

        // 0:待付款1:待发货2:待收货3:待评价4:完成5:退款中6:已退款7:待备货8:未备货退款
        return (List<PorderSend>) dao.findForList("OrderDao.orderSendList", map);
    }
    @Override
    public Map<String,Object> findWineApplyById(String id)throws Exception{
        Map<String,Object> map=(Map<String,Object>)dao.findForObject("OrderDao.findWineApplyById",id);
        return map;
    }

    @Override
    public void updateApplyState(String ids,String state,String approveMsg) throws Exception{
        Map map=new HashMap();
        map.put("ids",StringUtil.formatSqlIn(ids));
        map.put("state",state);
        map.put("approveMsg",approveMsg);
        dao.update("OrderDao.updateApplyState",map);
    }

    /**
     * 保存物流配送单号和配送方式
     * orderid 订单order_main 的id ，改变所有子订单的物流配送
     * sendType 0物流配送 1自己配送
     * logisticsCompany 快递公司名称
     * sendCode 快递单号
     */
    @Override
    public boolean saveOrderSend(String orderid, int sendType,
                                 String logisticsCompany, String sendCode) throws Exception {

        Map<String, Object> map = new HashMap<>();
        map.put("orderid", orderid);
        map.put("sendType", sendType);
        if(sendType==0)   //自提
        {
            map.put("logisticsCompany", "");
            map.put("sendCode", "");
        }else if(sendType==1)  //快递
        {
            map.put("logisticsCompany", logisticsCompany);
            map.put("sendCode", sendCode);
        }

        return (Integer) dao.update("OrderDao.updateOrderSend", map) > 0;
    }
    // 改变状态(所有main 下的子订单都改变状态)
    @Override
    public boolean updateBoolOrderState(String orderid, int state) throws Exception {

        Map<String, Object> map = new HashMap<>();
        map.put("orderid", orderid);
        map.put("state", state);
        // 0:待付款1:待发货2:待收货3:待评价4:完成5:退款中6:已退款7:待备货8:未备货退款
        boolean result= (Integer) dao.update("OrderDao.updateOrderDetailState", map) > 0;

        return result;
    }


    @Override
    public String findOpenId(String orderid) throws Exception {
        return (String) dao.findForObject("OrderDao.getOpenId",orderid);
    }
    @Override
    public PorderSend findPorderSend(String orderid) throws Exception {
        return (PorderSend) dao.findForObject("OrderDao.getPorderSend",orderid);
    }

    @Override
    public Map closeOrder(String orderMainId,String userCode)throws Exception{
        Map map = new HashMap();
        TorderMain torderMain = torderMainDao.getById(TorderMain.class,orderMainId);

        try{
            String status="0";
            String errormsg="退款异常啦";
            try {
                List<Map<String,Object>> detailList = (List<Map<String,Object>>)dao.findForList("OrderDao.findOrderDetailsByOrderId",torderMain.getId());
                if(detailList!=null && detailList.size()>0)
                {
                    for(int i=0;i<detailList.size();i++)
                    {
                        String openId="";
                        String buyUserId="";
                        String orderid="";
                        int goodsType=-1;//0:普通商品，1积分商品
                        String orderCode="";//订单code
                        Map<String,Object> map_q =null;
                        Map<String,Object> map_b =null;
                        Map<String,Object> map_m =null;//退现金

                        Map<String,Object> orderInfo = detailList.get(i);
                        openId = orderInfo.get("open_id").toString();
                        buyUserId = orderInfo.get("userId").toString();
                        orderid = orderInfo.get("id").toString();
                        orderCode=orderInfo.get("code").toString();
                        goodsType=Integer.parseInt(orderInfo.get("goodsType").toString());

                        BigDecimal scoreTotalDecimal = new BigDecimal(Double.valueOf(orderInfo.get("scoreTotal").toString()));

                        BigDecimal payTotalDecimal=new BigDecimal(Double.valueOf(orderInfo.get("payTotal").toString()));


                        int score = scoreTotalDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).intValue();
                        //退款金额
                        double refundMoney=payTotalDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();


                        boolean pd_q=false;
                        boolean pd_m=false;//现金 true:成功，false：成功
                        if(goodsType==1){   //积分商品
                            //返回积分
                            map_q = updateIntegralAndExperience(orderid,openId,score,"后台关闭订单");
                            if(map_q!=null){
                                if(map_q.get("flag").toString().equals("0")||map_q.get("flag").toString().equals("3")){
                                    pd_q=true;
                                }else{
                                    status=map_q.get("flag").toString();
                                    errormsg=map_q.get("msg").toString();
                                }
                            }
                        }else{    //普通商品
                            //退钱
                            map_m = updateRefundMoney(refundMoney,"1-"+orderCode);
                            if(map_m!=null){
                                if(map_m.get("flag").toString().equals("0")){
                                    pd_m=true;
                                }else{
                                    status=map_m.get("flag").toString();
                                    errormsg=map_m.get("msg").toString();
                                }
                            }
                        }




                        if(pd_q||pd_m){
                            //refundCallBack(result_map, id, openId, orderid, refundId, userId);//退款

                            //退库存
                            boolean update_kc=update_lm_jl_Ck(goodsType,orderid);

                            if(update_kc){
                           /*     Map<String, Object> detailmap = new HashMap<>();
                                detailmap.put("orderid", orderInfo.get("id").toString());
                                detailmap.put("state", 6);

                                // 0:待付款1:待发货2:待收货3:待评价4:完成5:退款中6:已退款7:待备货8:未备货退款
                                boolean a=(Integer) dao.update("OrderDao.updateOrderDetailidState", detailmap) > 0;
                         */       torderMain.setIsClosed(1);
                                torderMainDao.update(torderMain);
                            }else {
                                status="1";
                                errormsg="库存增加失败";
                            }
                        }
                    }
                    map.put("state",status);
                    map.put("msg",errormsg);
                }else
                {
                    map.put("state",status);
                    map.put("msg","无子订单数据");
                }


            } catch (Exception e) {
                map.put("state","1");
                map.put("msg","订单关闭异常啦");
            }
        }catch (Exception e){
            e.printStackTrace();
        }


        return map;
    }

    @Override
    public Paging queryRefundOrders(Map map) throws Exception {
        int limit = Integer.parseInt(map.get("limit").toString());
        int offset = Integer.parseInt(map.get("offset").toString());
        Pager<Map<String, Object>> pager = new Pager();
        pager.setParameters(map);
        pager.setStartRecord(offset);
        pager.setPageSize(limit);

        Pager<Map<String, Object>> pager_back = (Pager<Map<String, Object>>) dao.findForPager("OrderDao.findPageShopRefundOrder", "OrderDao.countShopRefundOrder", pager);
        //封装成适合前台使用的格式
        Paging paging = new Paging<>();
        paging.setRows(pager_back.getExhibitDatas());
        paging.setTotal((long) pager_back.getRecordCount());
        return paging;
    }

    // 改变字表状态(更具 字表id)
    public boolean updateStates(String orderDetailid, int detailState,String id,String refundState,String userId,String remarks) throws Exception {

        Map<String, Object> detailmap = new HashMap<>();
        detailmap.put("orderid", orderDetailid);
        detailmap.put("state", detailState);

        // 0:待付款1:待发货2:待收货3:待评价4:完成5:退款中6:已退款7:待备货8:未备货退款
        boolean a=(Integer) dao.update("OrderDao.updateOrderDetailidState", detailmap) > 0;

        if(Tools.isEmpty(remarks))
        {
            remarks="";
        }

        Map<String, Object> refundmap = new HashMap<>();
        refundmap.put("id", id);
        refundmap.put("state", refundState);
        refundmap.put("userId", userId);
        refundmap.put("remarks", remarks);

        boolean b=(Integer) dao.update("OrderDao.updateRefund", refundmap)>0;

        return a&&b;
    }

    @Override
    public Map<String,Object> updatesubmitToRefund(String id,String userId,String refundId,int paymentRoute,String remarks) throws Exception {    Map<String,Object> result_map = new HashMap<String,Object>();
        System.out.println("=======================>开始申请退款啦");
        System.out.println("paymentRoute="+paymentRoute);
        try {
            String total_fee="";
            String openId="";
            String buyUserId="";
            String orderid="";
            int goodsType=-1;//0:普通商品，1券类商品
            String orderCode="";//订单code
            Map<String,Object> map_q =null;
            Map<String,Object> map_b =null;
            Map<String,Object> map_m =null;//退现金

            Map<String,Object> orderInfo = findRefundInfoById(id);
            List<String> unRefundList= (List<String>) dao.findForList("OrderDao.findunRefundList",orderInfo);//判断是不是最后一个未退款的清单
            List<String> isSendOrderDetail= (List<String>) dao.findForList("OrderDao.findIsSendOrderDetailId",orderInfo);//判断还有没有未退款的订单或者已经发货了的订单

            total_fee = orderInfo.get("payTotal").toString();
           // String venderId = orderInfo.get("venderId").toString();
            openId = orderInfo.get("open_id").toString();
          //  buyUserId = orderInfo.get("userId").toString();
            orderid = orderInfo.get("id").toString();
            orderCode=orderInfo.get("code").toString();
            goodsType=Integer.parseInt(orderInfo.get("goodsType").toString());
            BigDecimal bigDecimal1 = new BigDecimal(Double.valueOf(orderInfo.get("balance_90").toString()));

            bigDecimal1 = new BigDecimal(bigDecimal1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            int balance_90 = bigDecimal1.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();

            BigDecimal bigDecimal4=new BigDecimal(Double.valueOf(orderInfo.get("money").toString()));

            if(unRefundList.size()<=0&&isSendOrderDetail.size()<=0)//当该笔退款订单为最后一个退款的子订单并且未发货的时候，退运费
            {
               bigDecimal4=new BigDecimal(Double.valueOf(orderInfo.get("money").toString())+Double.valueOf(orderInfo.get("freightTotal").toString()));
            }
            BigDecimal bigDecimal = new BigDecimal(Double.valueOf(total_fee));
            //退款金额
            double refundMoney=bigDecimal4.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

            String status="1";
            String errormsg="退款异常啦";
            boolean pd_q=false;//券 true:成功，false：成功
            if(goodsType==0){
                pd_q=true;
            }else{
                //返回券
                map_q = updateIntegralAndExperience(orderid,openId,balance_90,"用户退款审批成功");
                if(map_q!=null){
                    if(map_q.get("flag").toString().equals("0")||map_q.get("flag").toString().equals("3")){
                        pd_q=true;
                    }else{
                        status=map_q.get("flag").toString();
                        errormsg=map_q.get("msg").toString();
                    }
                }
            }

            boolean pd_m=false;//现金 true:成功，false：成功
            if(refundMoney>0){
                map_m = updateRefundMoney(refundMoney,"1-"+orderCode);
                if(map_m!=null){
                    if(map_m.get("flag").toString().equals("0")){
                        pd_m=true;
                    }else{
                        status=map_m.get("flag").toString();
                        errormsg=map_m.get("msg").toString();
                    }
                }
            }else
            {pd_m=true;}
            if(pd_q&&pd_m){
                //退库存
                boolean update_kc=update_lm_jl_Ck(goodsType,orderid);

                if(update_kc){
                    //保存订单
                    if(updateStates(orderid,6,refundId,"4",userId,remarks)){
                        status="0";
                        errormsg="";
                    }else{
                        status="1";
                        errormsg="保存状态失败";
                    }
                }else {
                    status="1";
                    errormsg="库存增加失败";
                }
            }

            result_map.put("status",status);
            result_map.put("errormsg",errormsg);
            result_map.put("balance_90",balance_90);
        } catch (Exception e) {
            result_map.put("status","1");
            result_map.put("errormsg","退款异常啦");
        }

        return result_map;
    }

    public Map<String,Object> findRefundInfoById(String id) throws Exception{
        return (Map<String,Object>)dao.findForObject("OrderDao.findRefundInfoById",id);
    }

    /**
     * 取消，加库存
     * @param goodsType 0:普通商品，1积分商品
     * @param detailId
     * @return
     */
    public boolean update_lm_jl_Ck(int goodsType,String detailId) throws Exception {
        String cityId="";
        try{
            cityId = Global.getLocalCity();
        }catch (Exception e)
        {
            e.printStackTrace();
        }

        Map<String, String> paramStockUp = new HashMap<>();
        paramStockUp.put("detailId", detailId);
        paramStockUp.put("cityId", cityId);

        PwxGoodsStockbak list = (PwxGoodsStockbak) dao.findForObject("OrderDao.getHistoryListUpStock", paramStockUp);

        boolean pd=false;

        if(list!=null){
                Map<String,Object> lm_cont=new HashMap<>();
                lm_cont.put("stockId",list.getLmStockId());
                lm_cont.put("count", list.getChangeNumber());
                dao.update("OrderDao.addStoreCount",lm_cont);
                pd=true;

        }

        return pd;


    }

    //0操作成功 1操作失败2余额不足3重复调用
    public Map<String,Object> updateRefundMoney(double refundMoney,String orderCode) throws Exception {
        Map<String,Object> map_r=new HashedMap();
        String flag="1";
        String msg="";
        int returnCode=1;
        try
        {


          //  Pay17BackPay backPay=pay17Service.getPay17_back(orderCode,orderCode,Global.getPay17_shop_code(),Global.getPay17_user_code(),(int)(refundMoney*100));
        //    msg=backPay.getReturn_info();
        //    returnCode =backPay.getReturn_code();
            if(returnCode==0){
                //错误
                flag="1";
            }else{
                flag="0";
            }

        } catch (Exception e)
        {
            flag="1";
            msg=e.getMessage();
        }finally {
            map_r.put("flag",flag);
            map_r.put("msg",msg);
        }
        return map_r;
    }
    //    0操作成功 1操作失败2余额不足3重复调用
    public Map<String,Object> updateIntegralAndExperience(String order_code,String openId,int score,String source_msg) throws Exception {
        String requestUrl= ConfigUtil.get("BALANCE_90")+"api/balance/operUserBalance.ac";
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,String > map1 =new HashMap<>();
        Map<String,Object> map_r = new HashMap<String,Object>();
        String flag="1";
        String msg="";
        try
        {
            if(score>0){
                map.put("order_code",order_code);
                map.put("open_id",openId);
                map.put("type",0);
                map.put("source","5");
                map.put("source_msg",source_msg);
                map.put("balance_90",String.valueOf(score));
                map.put("state",2);
                map1.put("json", JSON.toJSONString(map));
                String res= URLConectionUtil.httpURLConnectionPostDiy(requestUrl, map1);
                map.clear();
                map=JSON.parseObject(res,Map.class);
                flag=map.get("flag").toString();
                msg=map.get("msg").toString();
            }else{
                flag="0";
            }
        } catch (Exception e)
        {
            flag="1";
            msg=e.getMessage();
        }
        finally {
            map_r.put("flag",flag);
            map_r.put("msg",msg);
        }
        return map_r;
    }


    //退款信息详细（内容）
    @Override
    public Map<String, Object> orderRefund(String orderId) throws Exception {

        Map<String, Object> map = new HashMap<>();
        map.put("orderId", orderId);

        // 0:待付款1:待发货2:待收货3:待评价4:完成5:退款中6:已退款7:待备货8:未备货退款
        return (Map<String, Object>) dao.findForObject("OrderDao.orderRefundMx", map) ;

    }

    //退款信息详细（图片）
    @Override
    public List<Ppics> orderRefundPic(String orderId) throws Exception {

        Map<String, Object> map = new HashMap<>();
        map.put("orderId", orderId);

        // 0:待付款1:待发货2:待收货3:待评价4:完成5:退款中6:已退款7:待备货8:未备货退款
        return (List<Ppics>) dao.findForList("OrderDao.orderRefundMxPic", map);
    }
}
